<template>
  <div class="p-2">
    <a-spin size="large" :spinning="loading">
      <group-search :items="items" @chartLoad="init" v-if="head.dataType === 'sql' && !propsChartData" />
      <!-- <a-card style="margin-top:10px;text-align: center;" :title="false"  v-if="chartData.length<=0"> -->
      <!-- <h1 >没有查询到任何数据</h1> -->
      <div v-if="chartData.length <= 0" class="empty-warp">
        <a-empty />
      </div>
      <!-- </a-card> -->
      <div v-else id="printContent">
        <a-card :title="hiddenTitle ? '' : head.name" :bordered="false">
          <template #extra>
            <a-button type="primary" ghost @click="onPrint" ignore-print="true">打印</a-button>
          </template>
          <div v-if="!isOnlyTable()">
            <slot v-if="head.graphType !== 'table'" name="extra"></slot>
            <tab-graphreport-auto-chart
              v-if="head.displayTemplate === 'tab'"
              :chartData="chartData"
              :head="head"
              :graphTypeDictOptions="graphTypeDictOptions"
              :aliases="aliases"
            />
            <row-graphreport-auto-chart
              v-else-if="head.displayTemplate === 'single' || head.displayTemplate === 'double'"
              :chartData="chartData"
              :head="head"
              :graphTypeDictOptions="graphTypeDictOptions"
              :col="getCol()"
              :aliases="aliases"
            />
          </div>
        </a-card>
        <a-card
          :bordered="false"
          style="margin-top: 10px"
          :title="hiddenTitle ? '' : '数据明细'"
          v-if="getChartType('table') || getChartType('treeTable')"
        >
          <graphreport-auto-table v-if="getChartType('table')" :items="items" :cggraphreportData="cggraphreportData" :chartData="chartData" />
          <graphreport-auto-tree-table
            v-if="getChartType('treeTable')"
            :items="items"
            :cggraphreportData="cggraphreportData"
            :chartData="chartData"
          />
        </a-card>
      </div>
    </a-spin>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';
  import { useRoute } from 'vue-router';
  import { defHttp } from '/@/utils/http/axios';
  import { CHART_LIST } from '../utils/Utils';
  import TabGraphreportAutoChart from '../components/TabGraphreportAutoChart.vue';
  import RowGraphreportAutoChart from '../components/RowGraphreportAutoChart.vue';
  import GraphreportAutoTable from '../components/GraphreportAutoTable.vue';
  import GraphreportAutoTreeTable from '../components/GraphreportAutoTreeTable.vue';
  import GroupSearch from '../components/GroupSearch.vue';
  import { printJS } from '/@/hooks/web/usePrintJS';

  export default defineComponent({
    name: 'OnlGraphreportAutoChart',
    components: {
      TabGraphreportAutoChart,
      RowGraphreportAutoChart,
      GraphreportAutoTable,
      GraphreportAutoTreeTable,
      GroupSearch,
    },
    props: {
      propsChartData: {
        type: String,
        default: '',
      },
      id: {
        type: String,
        default: '',
      },
      hiddenTitle: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['register', 'success'],
    setup(props, { emit }) {
      const chartData = ref<any>([]);
      const head = ref<any>({});
      const items = ref<any>([]);
      const onlineGraphType = CHART_LIST; // 图表类型字典
      const loading = ref<boolean>(false);
      const cggraphreportData = ref<any>({});
      const aliases = ref<any>([]);

      const route = useRoute();

      init(null);

      const graphTypeDictOptions = computed(() => {
        return getGraphTypeDictOptions();
      });

      function getGraphTypeDictOptions() {
        // 获取需要渲染的图表类型
        var graphTypes = head.value.graphType ? head.value.graphType.split(',') : [];
        var charts = [];
        onlineGraphType.forEach(function (item, i) {
          if (graphTypes.indexOf(item.value) >= 0 && item.value !== 'table') {
            charts.push(item);
          }
        });
        return charts;
      }

      function init(queryParam) {
        if (props.propsChartData) {
          setChartData(JSON.parse(JSON.stringify(props.propsChartData)));
          loading.value = false;
          cggraphreportData.value = JSON.parse(JSON.stringify(props.propsChartData));
          setAliases(cggraphreportData);
        } else {
          const url = route.fullPath;
          const keyString = '/online/graphreport/chart/';
          let index = url.indexOf(keyString);
          let tmpId = url.substring(index + keyString.length);
          const id = props.id || tmpId;

          loading.value = true;

          if (queryParam) {
            queryParam = encodeURI(JSON.stringify(queryParam));
          }
          let params = {
            id: id,
            params: queryParam || '',
          };

          defHttp
            .get({ url: '/api-online/diagram/diagramConfiguration/getChartsData', params })
            .then((res) => {
              setChartData(res);
              setAliases(res);
              cggraphreportData.value = res;
            })
            .finally(() => {
              loading.value = false;
            });
        }
      }

      function setChartData(data) {
        // 设置基础data
        head.value = data.head;
        items.value = data.items;
        var sqlData = [];
        if (data.head.dataType === 'json' && data.head.cgrSql) {
          sqlData = JSON.parse(data.head.cgrSql.replace(/↵/g, ''));
        } else if (data.head.dataType === 'sql' || data.head.dataType === 'api') {
          sqlData = data.data;
        }
        chartData.value = sqlData;
      }

      function getCol() {
        const graphTypes = head.value.graphType.split(',');
        if (head.value.displayTemplate === 'single') {
          return { xl: 24, lg: 24, md: 24, sm: 24 };
        } else if (head.value.displayTemplate === 'double' && graphTypes.length > 1) {
          return { xl: 12, lg: 12, md: 12, sm: 12 };
        } else if (head.value.displayTemplate === 'double' && graphTypes.length <= 1) {
          return { xl: 24, lg: 24, md: 24, sm: 24 };
        }
        return {};
      }

      function getChartType(type) {
        // 获取是否包含改类型图表
        if (head.value.graphType) {
          const graphTypes = head.value.graphType.split(',');
          return graphTypes.indexOf(type) >= 0;
        } else {
          return false;
        }
      }

      function isOnlyTable() {
        // 判断是否只有table和treeTable
        if (head.value.graphType) {
          const graphTypes = head.value.graphType.split(',');
          let flag = false;
          switch (graphTypes.length) {
            case 1:
              flag = graphTypes.indexOf('table') >= 0 || graphTypes.indexOf('treeTable') >= 0;
              break;
            case 2:
              flag = graphTypes.indexOf('table') >= 0 && graphTypes.indexOf('treeTable') >= 0;
              break;
            default:
              flag = false;
          }
          return flag;
        } else {
          return false;
        }
      }

      function setAliases(data) {
        if (data.items) {
          data.items.forEach((item) => {
            aliases.value.push({
              field: item.fieldName,
              alias: item.fieldTxt,
            });
          });
        }
      }

      function onPrint() {
        const style = '@page {margin:0mm 10mm};'; //打印时去掉眉页眉尾
        printJS({
          printable: '#printContent',
          type: 'html',
          header: '',
          targetStyles: ['*'],
          style,
        });
      }

      return {
        chartData,
        head,
        items,
        onlineGraphType,
        loading,
        cggraphreportData,
        aliases,
        init,
        graphTypeDictOptions,
        isOnlyTable,
        getChartType,
        getCol,
        onPrint,
      };
    },
  });
</script>
<style scoped>
  .ant-table td {
    white-space: nowrap;
  }
  .empty-warp {
    height: 100%;
    width: 100%;
    padding: 10px;
    background-color: white;
  }
</style>
